<!--
 * @Author: Wangtao
 * @Date: 2022-09-01 10:39:01
 * @LastEditors: Wangtao
 * @LastEditTime: 2022-09-21 11:07:35
-->
<template>
  <div class="content" :class="{ 'record-box': !isCallCard, 'callcard-box': isCallCard }">
    <div class="left">
      <title-content class="title-content" :title="'客户信息'" adaption-height :isoprate="true">
        <template v-slot:content>
          <div class="list-box" v-if="customerNumStr === 'multiple'">
            <alert-msg content="此号码对应多个客户请先选择">
              <template #icon>
                <i class="MC_iconfont MC_icon-xinxi-mian"></i>
              </template>
            </alert-msg>
            <customer-list ref="customerListRef" :list="selectCustomerList"></customer-list>
          </div>
          <customer-form v-else ref="CustomerEdit" :form="form" :type="customerFormType"></customer-form>
        </template>
        <template v-slot:oprate>
          <el-button type="primary" @click="saveCustomer">保存</el-button>
        </template>
      </title-content>
    </div>
    <div class="right">
      <title-content class="title-content nopadding" :title="'客户动态'" adaption-height>
        <template v-slot:content>
          <customer-dynamic
            ref="CustomerRecord"
            :customerId="customerId"
            :showTitle="false"
            @onCallDetailShow="onCallDetailShow"
          ></customer-dynamic>
        </template>
      </title-content>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, watch, onMounted, ref, computed, getCurrentInstance } from 'vue'
import customerForm from '@app/customer/components/info-form.vue'

// 客户动态
import customerDynamic from '@app/customer/components/customer-dynamic/index.vue'
import { ElMessage } from 'element-plus'

import { cdrCustomerRelation, saveCustomer, updateCustomer } from '@app/base/apis/call'

import alertMsg from '@common/components/alert/index.vue'

// 定位客户
import customerList from '@app/call-center/views/recent-calls/component/tab-component/customDetail/customer-list.vue'

// 标题展示组件
import titleContent from '@app/call-center/views/recent-calls/component/tab-component/customDetail/title-content.vue'

import { deepClone } from '@/common/utils/common'

import { callCardModule } from '@/common/store/modules/call-card'

export default defineComponent({
  name: 'DetailCom',
  components: { customerForm, customerDynamic, titleContent, customerList, alertMsg },
  emits: ['onUpdateData'],
  props: {
    // 场景值 callcard 通话卡片 callrecord 通话记录详情
    scene: {
      type: String,
      default: 'callcard'
    },
    // 匹配客户列表
    customerList: {
      type: Array,
      default: () => {
        return []
      }
    },
    // 卡片信息-通话卡片
    cardInfo: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 通话详情信息
    callRcordInfo: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  setup(props) {
    const customerListRef: any = ref(null)
    const instance: any = getCurrentInstance()
    const CALLCARD = callCardModule()
    const state = reactive({
      form: {},
      selectCustomerList: [],
      currentCustomerList: [],
      customerNumStr: '',
      customerId: ''
    })

    const methods = reactive({
      // 获取号码关联客户关系
      async initCustomerInfo() {
        const CUSTOMERLIST: any = props.customerList
        const CURRENTPHONE: any = props.cardInfo.customerPhone
        if (CUSTOMERLIST.length > 1) {
          state.customerNumStr = 'multiple'
          state.currentCustomerList = CUSTOMERLIST
          state.selectCustomerList = CUSTOMERLIST.map((item: any) => {
            return {
              phone: CURRENTPHONE,
              name: item.customerName,
              _id: item._id
            }
          })
          state.customerId = ''
        } else if (CUSTOMERLIST.length === 1) {
          state.customerNumStr = 'single'
          state.form = CUSTOMERLIST[0]
          state.customerId = (state as any).form._id
        } else {
          state.customerNumStr = 'nomatch'
          state.form = {
            mobile: [{ value: CURRENTPHONE, memo: '' }]
          }
          state.customerId = ''
        }
      },
      async saveCustomer() {
        // 多个客户为切换
        if (state.customerNumStr === 'multiple') {
          if (customerListRef.value.currentRow) {
            ElMessage.warning('已选择')
            const customerId = customerListRef.value.currentRow._id

            state.currentCustomerList.some((item: any) => {
              if (item._id === customerId) {
                state.customerId = customerId
                state.form = item
                state.currentCustomerList = []
                return true
              }
            })
            state.customerNumStr = 'single'
            await cdrCustomerRelation({
              callId: props.cardInfo.superUniqueId,
              customerId: customerId,
              isUpdate: false
            })
            // 修改关联关系
            CALLCARD.updateCardInfo(props.cardInfo.superUniqueId, 'customerId', customerId)
            const setCustomerName =
              state.form && (state as any).form.customerName ? (state as any).form.customerName : ''
            CALLCARD.updateCardInfo(props.cardInfo.superUniqueId, 'customerName', setCustomerName)
            return
          } else {
            ElMessage.warning('请选择一个客户')
            return
          }
        }

        // 单个客户更新
        if (state.customerNumStr === 'single') {
          const editRes = await instance?.refs.CustomerEdit.isCheckForm()
          if (!editRes.status) {
            return
          }
          const saveForm = deepClone(editRes.form)
          saveForm.callId = props.cardInfo.superUniqueId
          const res = await updateCustomer(saveForm)
          if (res.success) {
            ElMessage.success('更新客户成功！')
            // 修改卡片关联关系
            CALLCARD.updateCardInfo(props.cardInfo.superUniqueId, 'customerId', saveForm._id)
            const setCustomerName =
              state.form && (state as any).form.customerName ? (state as any).form.customerName : ''
            CALLCARD.updateCardInfo(props.cardInfo.superUniqueId, 'customerName', setCustomerName)
            props.cardInfo.customerName = setCustomerName
          }
        }

        // 未匹配客户更新
        if (state.customerNumStr === 'nomatch') {
          const editRes = await instance?.refs.CustomerEdit.isCheckForm()
          if (!editRes.status) {
            return
          }
          const saveForm = deepClone(editRes.form)
          saveForm.callId = props.cardInfo.superUniqueId
          saveForm.createMethod = 'INSERT'
          const res = await saveCustomer(saveForm)
          if (res.success) {
            const returnData = res.data
            // 更新为单匹配客户
            state.customerNumStr = 'single'
            // 修改卡片关联关系
            ;(state as any).form._id = returnData._id
            CALLCARD.updateCardInfo(props.cardInfo.superUniqueId, 'customerId', returnData._id)
            const setCustomerName =
              state.form && (state as any).form.customerName ? (state as any).form.customerName : ''
            CALLCARD.updateCardInfo(props.cardInfo.superUniqueId, 'customerName', setCustomerName)
            props.cardInfo.customerName = setCustomerName
            // 更新客户动态id
            state.customerId = returnData._id
            ElMessage.success('添加客户成功！')
          }
        }
      },
      onCallDetailShow(callId: any) {
        CALLCARD.updateGlobalCardInfo('callId', callId)
        CALLCARD.updateGlobalCardInfo('show', true)
      }
    })

    watch(
      () => props.customerList,
      (newlist: any) => {
        if (newlist) {
          methods.initCustomerInfo()
        }
      },
      {
        immediate: true
      }
    )

    const isCallCard = computed(() => {
      return props.scene === 'callcard'
    })

    const customerFormType = computed(() => {
      return state.customerId ? 'edit' : 'add'
    })

    return {
      ...toRefs(state),
      ...toRefs(methods),
      customerListRef,
      isCallCard,
      customerFormType
    }
  }
})
</script>

<style lang="stylus" scoped>
.callcard-box
  .left
    flex: 1
    width: 0
.record-box
  .right
   display: none !important
  .left
    width 100%
.customer-list
  height: 100%
  .list-box
    height calc(100% - 48px)
    padding-top 20px
    box-sizing: border-box
  .oprate
    height: 48px
    border-top: 1px solid var(--mc-gray3-color);
    box-sizing: border-box
    display: flex
    align-items: center
.datetime-range
  width 100%
.content
  width 100%
  height: 100%
  display flex
  position relative
  box-sizing: border-box
  .right
    width: 640px
    display: flex
    padding-left: 24px
    border-left: 1px solid var(--mc-gray4-color)
    :deep(.el-form)
      flex-wrap nowrap
  .title-content
    width: 100%
    height: 100%
    box-sizing: border-box
</style>
